﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using PH.Model.Services;
namespace PH.Data.Services
{
    public class UserTokenCommand
    {
        public static UserTokenModel CreateNew(UserTokenModel model)
        {
            if (model!=null)
            {
                using (DBCentre db = new DBCentre())
                {
                    model.Token = Guid.NewGuid();
                    model.UpdateTime = DateTime.Now;
                    var old = db.DataContext.UserTokens.FirstOrDefault(p => p.Token == model.Token);
                    if (old != null)
                        Convertor.UpdateValue(model, old);
                    else
                    {
                        var d = Convertor.ConvertFrom<UserToken, UserTokenModel>(model);
                        db.DataContext.UserTokens.Add(d);
                    }
                    db.DataContext.SaveChanges();
                    return model;
                }
            }
            return null;
        }

        public static UserTokenModel GetModel(Guid token)
        {
            if (token != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.UserTokens.FirstOrDefault(p => p.Token == token);
                    if (d != null)
                    {
                        var ret = Convertor.ConvertTo<UserTokenModel, UserToken>(d);
                        return ret;
                    }
                }
            }
            return null;
        }
    }
}
